import 'dart:async';

import 'package:cloudapp/bus/dtypes.dart';
import 'package:cloudapp/esdk/db.dart';
import 'package:cloudapp/esdk/esync.dart';
import 'package:cloudapp/esdk/response/album_item_info.dart';
import 'package:cloudapp/items/album_item.dart';
import 'package:cloudapp/model/global_info.dart';
import 'package:cloudapp/model/upload_list.dart';
import 'package:cloudapp/pages/base.dart';
import 'package:cloudapp/pages/user_login_page.dart';
import 'package:cloudapp/utils/album_picture_diff.dart';
import 'package:cloudapp/utils/tasks.dart';
import 'package:cloudapp/widgets/my_stateful_builder.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'local_picture_page.dart';

class CloudAlbumPage extends StatefulWidget {
  static const pageName = "/cloud/album";
  @override
  State<StatefulWidget> createState() {
    return _CloudPicturePage();
  }
}

class _CloudPicturePage extends BaseState<CloudAlbumPage> {
  final List<AlbumItemInfo> _albumLists = [];

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, loadAlbums);
    Future.delayed(Duration(milliseconds: 100), loadLocalAlbums);
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> loadLocalAlbums() async {
    var sessionId = GlobalInfo.i().sessionId;
    print('sessionId: $sessionId');
    var left = await computeLeftAlbumFile(sessionId);
    print('left ${left.length}');
    var upList = Provider.of<UploadList>(context, listen: false);
    upList.initList(left);
  }

  void loadAlbums() async {
    await withExc(() async {
      final rs = await ESync.i().getAlbumList();
      setState(() {
        _albumLists.clear();
        for(var item in rs) {
          _albumLists.add(item);
        }
      });
    });
  }

  // 开启同步
  void startSync() {
    var upList = Provider.of<UploadList>(context, listen: false);
    upList.setSyncRun();
    execNextUpload(upList);
  }

  // 暂停同步
  void pauseSync() {
    var upList = Provider.of<UploadList>(context, listen: false);
    upList.setSyncPause();
  }

  @override
  Widget build(BuildContext context) {
    var children = <Widget>[];
    for(var item in _albumLists) {
      children.add(AlbumItem(
        album: item,
      ));
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('云相册'),
        actions: <Widget>[
          Consumer<UploadList>(
            builder: (BuildContext context, UploadList v, Widget child) {
              var label = "";
              switch (v.status) {
                case SyncStatus.Finished:
                  label = "开始上传";
                  break;
                case SyncStatus.Running:
                  label = "暂停上传";
                  break;
                case SyncStatus.Paused:
                  label = "继续上传";
                  break;
              }
              return PopupMenuButton(
                onSelected: (value) {
                  if(value == 'local-choose') {
                    Navigator.pushNamed(context, LocalPicturePage.pageName);
                  } else if(value == 'sync-action') {
                    syncAction(v.status);
                  } else if(value == 'sync-progress') {
                    showProgressDialog();
                  } else if(value == 'refresh') {
                    this.loadAlbums();
                    this.loadLocalAlbums();
                  } else if(value == 'logout') {
                    logoutClicked();
                  }
                },
                itemBuilder: (context) {
                  return <PopupMenuEntry>[
                    PopupMenuItem(
                      child: Text('刷新'),
                      value: 'refresh',
                    ),
                    PopupMenuItem(
                      child: Text('选择同步相册'),
                      value: 'local-choose',
                    ),
                    PopupMenuDivider(),
                    PopupMenuItem(
                      child: Text.rich(
                        TextSpan(
                            children: [
                              TextSpan(
                                text: label,
                              ),
                            ]
                        ),
                        textWidthBasis: TextWidthBasis.parent,
                        textAlign: TextAlign.justify,
                      ),
                      value: 'sync-action',
                    ),
                    PopupMenuItem(
                      child: Text('同步进度'),
                      value: 'sync-progress',
                    ),
                    PopupMenuDivider(),
                    PopupMenuItem(
                      child: Text('注销'),
                      value: 'logout',
                    ),
                  ];
                },
              );
            },
          ),
        ],
      ),
      body: Container(
        margin: const EdgeInsets.fromLTRB(1, 5, 0, 0),
        child: GridView.count(
          crossAxisCount: 4,
          childAspectRatio: 0.77,
          mainAxisSpacing: 1.0,
          crossAxisSpacing: 2.0,
          children: children,
        ),
      ),
    );
  }

  // 如果当前是同步中，即 _running=true 则界面显示的就是 暂停，则执行暂停同步逻辑
  void syncAction(SyncStatus status) {
    switch (status) {
      case SyncStatus.Finished:
        startSync();
        break;
      case SyncStatus.Running:
        pauseSync();
        break;
      case SyncStatus.Paused:
        startSync();
        break;
    }
  }

  Future<void> showProgressDialog() async {
    await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('相册同步进度'),
          content: MyStatefulBuilder(
            dispose: () {
              //
            },
            builder: (context, setState) {
              return Consumer<UploadList>(
                builder: (context, value, child) {
                  return Container(
                    child: Text(
                      '剩余 ${value.leftLength} 文件未同步, 已同步 ${value.finishedCount}'
                    ),
                  );
                },
              );
            },
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('返回'),
              onPressed: () {
                Navigator.of(context).pop(true);
              },
            )
          ],
        );
      }
    );
  }

  /// 注销用户流程
  /// 1. 发请求到服务器，异步，忽略成功或失败
  /// 2. 删除会话数据 忽略失败 // 不应该删除，应保留，会话ID是唯一标识 // 应清空token值
  /// 3. 全局 SessionId 清空
  /// 4. ESync 清空 token
  /// 5. 跳转
  void logoutClicked() async {
    var sessionId = GlobalInfo.i().sessionId;

    ESync.i().userLogout();
    DbStorage.i().delSessionToken(sessionId);
    GlobalInfo.i().setSessionId(0);
    ESync.i().setToken(0, "");
    await Navigator.pushNamedAndRemoveUntil(context, UserLoginPage.pageName, (route) => false);
  }
}
